package com.yeepay.skb.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeepay.skb.results.YeepayResult;
import com.yeepay.skb.util.Conts;
import com.yeepay.skb.util.Digest;
import com.yeepay.skb.util.SignUtil;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.methods.multipart.StringPartTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class YeepayBuilder {
    private static final Logger logger = LoggerFactory.getLogger(YeepayBuilder.class);

    protected String url;

    abstract Part[] generateParams();
    abstract void setHmac(String hmac);

    /**
     * 需要加签的字段
     * @return
     */
    abstract List<String> needHmacArr();

    public abstract String getUrl();

    public <T extends YeepayResult> T exec(Class<T> c) throws IOException {
        Part[] parts=generateParams();
        setHmac(SignUtil.signHmac(parts,needHmacArr()));
        PostMethod postMethod = new PostMethod(getUrl());
        try{
        HttpClient client = new HttpClient();
        postMethod.setRequestEntity(new MultipartRequestEntity(generateParams(),
                postMethod.getParams()));
        int status = client.executeMethod(postMethod);
        if (status == HttpStatus.SC_OK) {
            String resstr=postMethod.getResponseBodyAsString();
            T res=JSONObject.toJavaObject(JSONObject.parseObject(resstr),c);
            if (!res.imSuccess()) {
                logger.error(logErr(parts)+":"+resstr);
            }
            return res;
//        } else if (status == HttpStatus.SC_MOVED_PERMANENTLY
//                || status == HttpStatus.SC_MOVED_TEMPORARILY) {
            // 从头中取出转向的地址
//            Header locationHeader = postMethod
//                    .getResponseHeader("location");
//            String location = null;
//            if (locationHeader != null) {
//                location = locationHeader.getValue();
//                System.out
//                        .println("The page was redirected to:" + location);
//            } else {
//                System.err.println("Location field value is null.");
//            }
//        } else {
//            System.out.println("fail======" + status);
        }else{
            logger.error(logErr(parts)+":请求失败");
        }

        }finally {
            postMethod.releaseConnection();
        }
        return null;
    }

    public String logErr(Part[] params) throws IOException {
        String charSet="UTF-8";
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        try {
            for(Part p:params){
                if (p != null&&p instanceof StringPart) {
                    StringPart sp= (StringPart) p;
                    baos.write(("\""+sp.getName()+"\":\"").getBytes());
                    new StringPartTool(sp).getValue(baos);
                    baos.write("\",".getBytes());
                    charSet=sp.getCharSet();
                }
            }
        } finally {
            baos.close();
        }
        return new String(baos.toByteArray(),charSet);
    }
}
